package yur.wedding.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import yur.wedding.modules.sys.dao.SysUserDao;

import yur.wedding.modules.sys.entity.SysDictEntity;
import yur.wedding.modules.sys.entity.SysUserEntity;
import yur.wedding.modules.sys.service.SysDictService;
import yur.wedding.modules.sys.service.SysUserTokenService;
import yur.wedding.modules.sys.shiro.ShiroUtils;
import yur.wedding.utils.R;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * 登陆
 *
 * @Author: Yur
 * @Data:2021/11/12 23:01
 */
@Controller
public class SysLoginController {

    @Autowired
    private Producer producer;
    @Resource
    private SysUserDao sysUserDao;

    @Autowired
    private SysDictService sysDictService;
    @Resource
    private SysUserTokenService sysUserTokenService;

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        System.out.println("验证码值" + text);
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }


    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public R login(String username, String password, String captcha) {

        List<SysDictEntity> entities = sysDictService.loginimgpathlist();
        for (SysDictEntity dict:entities) {
            if (dict.getCode()== "yzm" && dict.getValue()!="0") {
                //显示验证码 时校验
                String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
                if (!captcha.equalsIgnoreCase(kaptcha)) {
                    return R.error("验证码不正确");
                }

            }
        }


        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
        System.out.println(R.ok());
        return R.ok();

    }
    @ResponseBody
    @GetMapping("/sys/selectByUserName")
    public R selectByUserName() {
        //  通过shior 获取当前登录的user  并收取IP

        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        System.out.println("---"+principal);
        return R.ok().put("principal", principal);
    }


    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        ShiroUtils.logout();
        HttpSession session=request.getSession();
        session.invalidate();
        return "redirect:login.html";
    }

    @RequestMapping("/login")
    public String loginit() {

        return "login";
    }


}
